<template>
  <div class="editor-container">
    <div id="editor-box"></div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import E from 'wangeditor'
import { editArticle, commitArticle } from "./commit"
import { watch } from 'vue'
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  detailData: {
    type: Object,
    default: () => { }
  }
})

const emits = defineEmits(['onSuccess'])
let editor
onMounted(() => {
  const el = document.querySelector('#editor-box')
  initEditor(el)
})
watch(() => props.detailData.content, (newVal) => {
  if (newVal) {
    editor.txt.html(newVal)
  }
})
const initEditor = (el) => {
  editor = new E(el)
  editor.config.zIndex = 1
  // 菜单栏提示
  editor.config.showMenuTooltips = true
  editor.config.menuTooltipPosition = 'down'

  // 国际化相关处理
  editor.config.lang = 'zh-CN'

  editor.create()
}

const onSubmitClick = async () => {
  if (props.detailData._id) {
    // 编辑文章
    await editArticle({
      id: props.detailData._id,
      title: props.title,
      content: editor.txt.html()
    })
  } else {
    // 创建文章
    await commitArticle({
      title: props.title,
      content: editor.txt.html()
    })
  }

  editor.txt.html('')
  emits('onSuccess')
}
</script>

<style lang="scss" scoped>
.editor-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>